<?php

namespace App\Http\Controllers\Admin;

use App\Models\ActivitySale as Coupon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\LayuiController as Layui;
use App\Exceptions\FormException;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Validator;
use Mockery\Exception;

class CouponController extends Controller
{
    /**
     * 列表页面
     *
     * @Author   stonefall
     * @DateTime 2019-06-5
     * @return   [type]     [description]
     */
    public function index()
    {
        return view('Admin.coupon.index');
    }

    /**
     * 获取数据
     * @return [json]           [数组格式]
     */
    public function table(Request $request)
    {
        $payload = $request->all();
        $activityData = Coupon::orderBy('id', 'DESC')
            ->where(function ($query) use ($payload) {
                $query->Where('activity_type', Coupon::RULE_TYPE_TWO);
                $query->Where('issue_type', 1);
                if (isset($payload['activity_name']) && $payload['activity_name'] != '') {
                    $query->Where('activity_name','like' , '%' . $payload['activity_name'] . '%');
                }
            })
            ->paginate($request->get('limit', 10));
        return Layui::tableJson($activityData, 0, 1);
    }


    /**
     * 添加页面
     *
     * @Author   stonefall
     * @DateTime 2019-06-5
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function create()
    {
        if (View::exists('Admin/coupon/add')) {
            return view('Admin/coupon/add');
        } else {
            return 'View Not Found';
        }
    }

    /**
     * 添加请求
     *
     * @Author   stonefall
     * @DateTime 2019-06-5
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function store(Request $request)
    {

        $payload = $request->all(['activity_name', 'full', 'less', 'rule_type', 'start_at', 'end_at']);
        $rule = [
            'activity_name' => 'required',
//            'less' => 'required|numeric',
            'rule_type' => 'required|in:1,2',//
            'end_at' =>  'required|date|after_or_equal:start_at',
            'start_at' => 'required|date',
            'full' => ['required_if:rule_type,2', function($attribute, $value, $fail) {
                if ($value){
                    if (!preg_match('/^[0-9]+$/',$value)  ) {
                        return $fail('满多少请输入数字');
                    }
                }
            }],
            'less' => ['required','numeric', function($attribute, $value, $fail) {
                if ($value){
                    if (!preg_match('/^[0-9]+$/',$value)  ) {
                        return $fail('减多少请输入数字');
                    }
                }
            }],
        ];
        if ($payload['rule_type'] == Coupon::RULE_TYPE_TWO){
            if ((int)$payload['full'] < (int)$payload['less']){
                throw new FormException('满多少请输入大于等于减的数字');
            }

        }
        $message = [
            'activity_name.required' => '请输入活动名称',
            'less.required' => '请输入减多少',
            'less.numeric' => '减多少请输入数字',
            'rule_type.in' => '请选择优惠类型',//
            'start_at.date' => '输入正确的时间',
            'end_at.date' => '输入正确的时间',
            'end_at.after_or_equal' => '结束时间应大于开始时间',
        ];
        Validator::make($payload, $rule, $message)->validate();

        $payload['activity_type'] = Coupon::RULE_TYPE_TWO;

        try {
            Coupon::create($payload);
        } catch (\Exception $exception) {
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败');
        }
        return $this->getResponseSuccess('保存成功', route('coupon.index'));
    }


    /**
     * 编辑页面
     *
     * @Author   stonefall
     * @DateTime 2019-05-31
     * @param    Request $request [description]
     * @return   [type]                [description]
     */
    public function edit($id)
    {
        if (View::exists('Admin/coupon/edit')) {
            $data = Coupon::find($id);
            $data['end_at'] = substr($data['end_at'],0,10);
            $data['start_at'] =substr($data['start_at'],0,10);
            return view('Admin/coupon/edit', compact('data'));
        } else {
            return 'View Not Found';
        }
    }

    /**
     * 修改请求
     *
     * @Author   stonefall
     * @DateTime 2019-05-31
     * @param    Request $request [description]
     * @return   [type]                [description]
     */
    public function update(Request $request, $id)
    {

        $payload = $request->all(['activity_name']);

        $rule = [
            'activity_name' => 'required',
        ];
        $message = [
            'activity_name.required' => '请输入活动名称',
        ];
        Validator::make($payload, $rule, $message)->validate();
        try {
            if ($id) {
                Coupon::where(['id' => $id])->update($payload);
            } else {
                throw new Exception('参数错误');
            }
        } catch (\Exception $exception) {
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败');
        }
        return $this->getResponseSuccess('保存成功', route('coupon.index'));
    }


}
